package com.education.wisdom.controller;

import com.education.common.config.BusinessException;
import com.education.common.config.CommonErrorCode;
import com.education.common.config.WebSocketServer;
import com.education.common.pojo.CatalogResultVO;
import com.education.common.pojo.OResources;
import com.education.common.pojo.SQuestionsVO;
import com.education.common.utils.*;
import com.education.wisdom.feign.UserFeign;
import com.education.wisdom.pojo.*;
import com.education.wisdom.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

import static com.education.common.core.BaseController.writeJSON;


/**
 * 目录体系 信息操作处理
 *
 * @author ruoyi
 * @date 2018-11-15
 */
@Controller
@CrossOrigin
@Slf4j
@ResponseBody
@Api(tags = {"专业课程体系目录"})
@RequestMapping("/web/catalog")
public class FullCatalogController {

    @Autowired
    private ICatalogService catalogService;

    @Autowired
    private IPaperService paperService;

    @Autowired
    private IUserCatalogBuyService userCatalogBuyService;

    @Autowired
    private IResourcesService resourcesService;

    @Autowired
    private ICommentsService commentsService;

    @Autowired
    private ISysAppLoginService loginService;

    @Autowired
    private IUserAccountService accountService;

    @Autowired
    private ICollectionsService collectionsService;

    @Autowired
    private ILabelService labelService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ICatalogUserLikeService userLikeService;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private ICurrencyRecordService currencyRecordService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private IQuestionsService questionsService;

    @Autowired
    private IJrPaperQueRelationService queRelationService;

    @Autowired
    private ICatalogUserService catalogUserService;

    @Autowired
    private JrProfeUserService jrProfeUserService;

    @Autowired
    private RulesService rulesService;


    @GetMapping("/insUserBuy")
    public void insUserBuy(@RequestParam("userId") Integer userId, @RequestParam("tId") Integer tId) {
        Integer[] catalogIds = userCatalogBuyService.selectCatalogIdByUserId(tId);
        for (Integer catalogId : catalogIds) {
            UserCatalogBuy buy = new UserCatalogBuy();
            buy.setCatalogId(catalogId);
            buy.setUserId(userId.toString());
            buy.setItFrom(2);
            userCatalogBuyService.insert(buy);
        }
    }

    /**
     * 管理端为教务主任分配资源
     *
     * @param userCatalogBuy
     * @return
     */
    @PostMapping("/userBuy")
    public ApiReturnObject userBuy(@RequestBody UserCatalogBuy userCatalogBuy) {
        //Integer[] arr = catalogService.selectByCatalogIdParentId(0);//一级目录
        //Integer[] array = catalogService.selectCatalogIds();//二级目录
        //Integer[] catalogIds = new Integer[arr.length + array.length];//目录数量
        //System.arraycopy(arr, 0, catalogIds, 0, arr.length);
        //System.arraycopy(array, 0, catalogIds, arr.length, array.length);
        //List<Integer> sort = sort(catalogIds, userCatalogBuy.getCatalogArray());

        List<Integer> list = userFeign.selectBySchooleId(userCatalogBuy.getSchoolId());

        for (Integer userId : list) {
            userCatalogBuyService.deleteByUserId(userId.toString());
            if (null != userCatalogBuy.getCatalogArray() && userCatalogBuy.getCatalogArray().length > 0) {
                for (Integer catalogId : userCatalogBuy.getCatalogArray()) {
                    UserCatalogBuy buy = new UserCatalogBuy();
                    buy.setUserId(userId.toString());
                    buy.setCatalogId(catalogId);
                    buy.setItFrom(2);
                    buy.setDeflag("1");
                    userCatalogBuyService.insert(buy);
                }
            }
        }
        return new ApiReturnObject("200", "", "");
    }

    private List<Integer> sort(Integer[] array, Integer[] param) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < i; j++) {
                if (array[i] < array[j]) {
                    int temp = array[i];
                    array[i] = array[j];
                    array[j] = temp;
                }
            }
        }
        for (Integer id : param) {
            if (search(array, id)) {
                list.add(id);
            }
        }
        return list;
    }

    private boolean search(Integer[] arr, int value) {
        //定义中间元素下标
        int low = 0;
        int high = arr.length - 1;
        while (low <= high) {
            int min = low + (high - low) / 2;
            if (arr[min] == value) {
                //当值相等 则返回数组下标
                return false;
            } else if (arr[min] < value) {
                //值小于传入的元素 则说明该元素在数组的右面
                low = min + 1;
            } else {
                //否则在左边
                high = min - 1;
            }
        }
        return true;
    }


    @GetMapping("/selectBuy")
    public Integer[] selectBuy(Integer userId) {
        return userCatalogBuyService.selectCatalogIdByUserId(userId);
    }

    @GetMapping("/profLike")
    public ApiReturnObject profLike(Integer userId, Integer pageNum, Integer pageSize) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<Catalog> list = catalogService.selectLikeByUserId(userId);
        list.forEach(item -> {
            List<Catalog> catalogs = catalogService.selectByCatalogId(item.getParentId());
            item.setParentName(catalogs.get(0).getName());
            item.setParentCatalogId(catalogs.get(0).getCatalogId().toString());
        });
        return new ApiReturnObject("200", "", new PageInfo<Catalog>(list));
    }


    /**
     * 目录筛选 && 搜索
     *
     * @param catalogId
     * @param userId
     * @param type      1 已购买 0 未购买
     * @return
     */
    @GetMapping("/Screen")
    public ApiReturnObject screen(Integer catalogId, Integer userId, String name, Integer type, Integer schoolId, Integer pageNum, Integer pageSize) {
        //分页
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        if (userId == null || type == null) {
            //如果usrid==null，type==null，就返回一个三级目录
            List<Catalog> catalogs = catalogService.selectByParentIdAndSort(catalogId, 3);

            if (catalogs.size() > 0) {
                return new ApiReturnObject("200", "success", new PageInfo<Catalog>(catalogs));
            }

            List<Catalog> list = catalogService.selectCatalogByOne(catalogId, name);
            return new ApiReturnObject("200", "success", new PageInfo<Catalog>(list));
        }
        //catalogId 2679是实训教学资源
        if (userId == 1043 && catalogId == 2679) {
            return new ApiReturnObject("200", "success", new PageInfo<Catalog>(new ArrayList<>()));
        }

        //TODO catalogId不传递 查找全部二级目录id
        List<Integer> catalog = new ArrayList<>();
        if (Objects.nonNull(catalogId)) {
            catalog.add(catalogId);
        } else {
            catalog = catalogService.selectALLTwoLevelMenus();
        }

        if (type == 1) {

            //一级目录查不出三级 二级目录查出三级
            List<Catalog> catalogList = catalogService.isBuy(userId, catalog, name, schoolId);
            if (catalogList.size() == 0) {
                List<Integer> ids = new ArrayList<>();
                List<Catalog> catalogs = catalogService.selectByParentId(catalogId);
                for (Catalog catalog1 : catalogs) {
                    ids.add(catalog1.getCatalogId());
                }

                if (ids.size() == 0) {
                    return new ApiReturnObject("200", "success", new PageInfo<Catalog>(new ArrayList<>()));
                }

                List<Catalog> catalogList1 = catalogService.isBuy(userId, ids, name, schoolId);
                catalogList1.forEach(item -> {
                    isLike(userId, item);
                });
                return new ApiReturnObject("200", "success", new PageInfo<Catalog>(catalogList1));
            }
            catalogList.forEach(item -> {
                isLike(userId, item);
            });
            return new ApiReturnObject("200", "success", new PageInfo<Catalog>(catalogList));
        } else if (type == 0) {

            //一级目录查不出三级 二级目录查出三级
            List<Catalog> catalogList = catalogService.isNotBuy(userId, catalog, name, schoolId);
            if (catalogList.size() == 0) {
                List<Integer> ids = new ArrayList<>();
                List<Catalog> catalogs = catalogService.selectByParentId(catalogId);
                for (Catalog catalog1 : catalogs) {
                    ids.add(catalog1.getCatalogId());
                }
                if (ids.size() == 0) {
                    return new ApiReturnObject("200", "success", new PageInfo<Catalog>(new ArrayList<>()));
                }

                List<Catalog> catalogList1 = catalogService.isNotBuy(userId, ids, name, schoolId);
                catalogList1.forEach(item -> {
                    isLike(userId, item);
                });
                return new ApiReturnObject("200", "success", new PageInfo<Catalog>(catalogList1));
            }
            catalogList.forEach(item -> {
                isLike(userId, item);
            });
            return new ApiReturnObject("200", "success", new PageInfo<Catalog>(catalogList));
        }
        return new ApiReturnObject("200", "failure", new PageInfo<Catalog>(new ArrayList<>()));
    }

    /**
     * 给Catalog对象符是否收藏的值
     *
     * @param userId
     * @param item
     */
    private void isLike(Integer userId, Catalog item) {
        JrProfeUser jrProfeUser = new JrProfeUser();
        jrProfeUser.setUserId(userId);
        jrProfeUser.setCatalogId(item.getCatalogId());
        List<JrProfeUser> jrProfeUsers = jrProfeUserService.selectJrProfeUserList(jrProfeUser);
        if (StringUtils.isEmpty(jrProfeUsers)) {
            //未收藏
            item.setIsLike(0);
        } else {
            //已收藏
            item.setIsLike(1);
        }
    }

    @GetMapping("/catalogList")
    @ApiOperation("查询专业大类体系列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "登录用户id", dataType = "String")})
    public void catalogList(HttpServletResponse response) throws Exception {
        log.info(LogUtil.LogInfo("查询专业大类体系列表", new Date()));
//        String catalog = redisTemplate.boundValueOps("webCatalog").get();
//        if (catalog != null && catalog.length() > 0) {
//            writeJSON(catalog, response, "200", "成功");
//        } else {
        List<Catalog> catalogs = catalogService.selectTwoCatalogList();
//            catalog = JSON.toJSONString(catalogs);
//            redisTemplate.boundValueOps("webCatalog").set(catalog);
        writeJSON(catalogs, response, "200", "成功");
//        }
    }

    @GetMapping("/newList")
    @ResponseBody
    @ApiOperation("查询最新课程")
    public void newList(HttpServletResponse response, String userId, Integer count, Integer pageSize, Integer pageNum) throws Exception {
        log.info(LogUtil.LogInfo("查询最新课程", new Date()));
        SysAppLogin appLogin = loginService.selectSysAppLoginById(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("count", count);
        //未登录
        if (appLogin == null) {
            if (count == null) {
                PageHelper.startPage(pageNum, pageSize);
            }
            List<Catalog> list = catalogService.newClass(map);
            for (Catalog catalog : list) {
                catalog.setIsRed("0");
            }
            writeJSON(new PageInfo<>(list), response, "200", "成功");
        } else {
            //登录
            //1普通用户
            if (appLogin.getCustomerType().equals("1")) {
                if (count == null) {
                    PageHelper.startPage(pageNum, pageSize);
                }
                List<Catalog> list = catalogService.newClass(map);
                for (Catalog catalog : list) {
                    Map<String, Object> hashmap = new HashMap<>();
                    hashmap.put("userId", appLogin.getUserId());
                    hashmap.put("catalogId", catalog.getCatalogId());
                    UserCatalogBuy userCatalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(hashmap);
                    if (userCatalogBuy == null) {
                        catalog.setIsRed("0");
                    } else {
                        catalog.setIsRed("1");
                    }
                }
                writeJSON(new PageInfo<>(list), response, "200", "成功");
            } else {
                //2线下分配用户
                Map<String, Object> map2 = new HashMap<>();
                map2.put("schoolId", appLogin.getSchoolId());
                map2.put("userType", "2");
                SysAppLogin login = loginService.selectByDeptId(map2);
                if (count == null) {
                    PageHelper.startPage(pageNum, pageSize);
                }
                List<Catalog> list = catalogService.newClass(map);
                for (Catalog catalog : list) {
                    Map<String, Object> hashmap = new HashMap<>();
                    hashmap.put("userId", login.getUserId());
                    hashmap.put("catalogId", catalog.getCatalogId());
                    UserCatalogBuy userCatalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(hashmap);
                    if (userCatalogBuy == null) {
                        catalog.setIsRed("0");
                    } else {
                        catalog.setIsRed("1");
                    }
                    Map<String, Object> objectMap = new HashMap<>();
                    objectMap.put("userId", userId);
                    objectMap.put("catalogId", catalog.getCatalogId());
                    UserCatalogBuy catalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(objectMap);
                    if (catalogBuy != null) {
                        catalog.setIsRed("1");
                    }
                }
                writeJSON(new PageInfo<>(list), response, "200", "成功");
            }
        }
    }

    //获取父级的父级目录id以及名称
    private void getFirstCatalog(Catalog catalog) {
        Catalog catalog2 = catalogService.selectCatalogByCatalogId(catalog.getParentId());
        if (catalog2 != null) {
            Catalog catalog1 = catalogService.selectCatalogByCatalogId(catalog2.getParentId());
            if (catalog1 != null) {
                catalog.setParentCatalogId(catalog1.getCatalogId() + "");
                catalog.setParentCatalogName(catalog1.getName());
            } else {
                catalog.setParentCatalogId("");
                catalog.setParentCatalogName("");
            }
        }
    }

    /**
     * 今软职业教育信息化平台
     * 首页-专业课程体系
     * 查询热门课程
     *
     * @param response
     * @param userId   用户id
     * @param count    返回个数
     * @param pageSize
     * @param pageNum
     * @throws Exception
     */
    @GetMapping("/hotClass")
    @ResponseBody
    @ApiOperation("查询热门课程")
    public void hotClass(HttpServletResponse response, Integer userId, Integer count, Integer pageSize, Integer pageNum) throws Exception {
        log.info(LogUtil.LogInfo("查询热门课程", new Date()));
        Map<String, Object> appLogin = userFeign.selectByUserId(userId);

        Map<String, Object> map = new HashMap<>();
        map.put("count", count);
        //未登录 没有传userId
        if (appLogin.size() == 0) {
            if (count == null) {
                if (pageNum != null && pageSize != null) {
                    PageHelper.startPage(pageNum, pageSize);
                }
            }
            List<Catalog> list = catalogService.hotClass(map);
            for (Catalog catalog : list) {
                //获取祖籍信息
                getFirstCatalog(catalog);
                catalog.setIsRed("0");
            }
            writeJSON(new PageInfo<>(list), response, "200", "成功");
        } else {
            //登录
            //1普通用户
            /*if (appLogin.get("CustomerType").equals("1")) {
                if (count == null) {
                    if (pageNum != null && pageSize != null) {
                        PageHelper.startPage(pageNum, pageSize);
                    }
                }
                //根据课程学习次数排名排序
                List<Catalog> list = catalogService.hotClass(map);
                for (Catalog catalog : list) {
                    getFirstCatalog(catalog);
                    Map<String, Object> hashmap = new HashMap<>();
                    hashmap.put("userId", userId);
                    hashmap.put("catalogId", catalog.getCatalogId());
                    UserCatalogBuy userCatalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(hashmap);
                    if (userCatalogBuy == null) {
                        catalog.setIsRed("0");//未购买
                    } else {
                        catalog.setIsRed("1");//已购买
                    }
                }
                writeJSON(new PageInfo<>(list), response, "200", "成功");
            } else {*/
            //2线下分配用户
                /*Map<String, Object> map2 = new HashMap<>();
                map2.put("schoolId", appLogin.get("SchoolId"));
                map2.put("userType", "2");
                SysAppLogin login = loginService.selectByDeptId(map2);*/
            //查找特定学校的老师
            Map<String, Object> login = userFeign.selectBySchoolIdAndType(Integer.parseInt(appLogin.get("SchoolId").toString()), 2);
            if (count == null) {
                if (pageNum != null && pageSize != null) {
                    PageHelper.startPage(pageNum, pageSize);
                }
            }
            //根据课程学习次数排名排序
            List<Catalog> list = catalogService.hotClass(map);
            for (Catalog catalog : list) {
                getFirstCatalog(catalog);
                //查找分配给学校的资源
                Map<String, Object> hashmap = new HashMap<>(2);
                hashmap.put("userId", login.get("userId"));
                if (null != userId) {
                    hashmap.put("userId", userId);
                }
                hashmap.put("catalogId", catalog.getCatalogId());
                UserCatalogBuy userCatalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(hashmap);
                if (userCatalogBuy == null) {
                    catalog.setIsRed("0");
                } else {
                    catalog.setIsRed("1");
                }
                //查找当前老师购买的资源
                Map<String, Object> objectMap = new HashMap<>();
                objectMap.put("userId", userId);
                objectMap.put("catalogId", catalog.getCatalogId());
                UserCatalogBuy catalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(objectMap);
                if (catalogBuy != null) {
                    catalog.setIsRed("1");
                }
            }
            writeJSON(new PageInfo<>(list), response, "200", "成功");
            //}
        }
    }

    @GetMapping("/userLike")
    @ResponseBody
    @ApiOperation("猜你喜欢列表展示")
    @ApiImplicitParam(name = "userId", value = "用户编号", dataType = "String")
    public void userLike(HttpServletResponse response, String userId, Integer count, Integer pageSize, Integer pageNum) throws Exception {
        log.info(LogUtil.LogInfo("猜你喜欢列表展示", new Date()));
        SysAppLogin appLogin = loginService.selectSysAppLoginById(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("count", count);
        //未登录
        if (appLogin == null) {
            if (count == null) {
                PageHelper.startPage(pageNum, pageSize);
            }
            List<Catalog> list = catalogService.selectList(map);
            for (Catalog catalog : list) {
                catalog.setIsRed("0");
            }
            writeJSON(new PageInfo<>(list), response, "200", "成功");
        } else {
            //登录
            //1普通用户
            if (appLogin.getCustomerType().equals("1")) {
                if (count == null) {
                    PageHelper.startPage(pageNum, pageSize);
                }
                List<Catalog> list = catalogService.selectList(map);
                for (Catalog catalog : list) {
                    Map<String, Object> hashmap = new HashMap<>();
                    hashmap.put("userId", appLogin.getUserId());
                    hashmap.put("catalogId", catalog.getCatalogId());
                    UserCatalogBuy userCatalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(hashmap);
                    if (userCatalogBuy == null) {
                        catalog.setIsRed("0");
                    } else {
                        catalog.setIsRed("1");
                    }
                }
                writeJSON(new PageInfo<>(list), response, "200", "成功");
            } else {
                //2线下分配用户
                Map<String, Object> map2 = new HashMap<>();
                map2.put("schoolId", appLogin.getSchoolId());
                map2.put("userType", "2");
                SysAppLogin login = loginService.selectByDeptId(map2);
                if (count == null) {
                    PageHelper.startPage(pageNum, pageSize);
                }
                List<Catalog> list = catalogService.selectList(map);
                for (Catalog catalog : list) {
                    Map<String, Object> hashmap = new HashMap<>();
                    hashmap.put("userId", login.getUserId());
                    hashmap.put("catalogId", catalog.getCatalogId());
                    UserCatalogBuy userCatalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(hashmap);
                    if (userCatalogBuy == null) {
                        catalog.setIsRed("0");
                    } else {
                        catalog.setIsRed("1");
                    }
                    Map<String, Object> objectMap = new HashMap<>();
                    objectMap.put("userId", userId);
                    objectMap.put("catalogId", catalog.getCatalogId());
                    UserCatalogBuy catalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(objectMap);
                    if (catalogBuy != null) {
                        catalog.setIsRed("1");
                    }
                }
                writeJSON(new PageInfo<>(list), response, "200", "成功");
            }
        }
    }

    @GetMapping("/threeLevelDirectory")
    @ApiOperation("查询专业大类3级目录")
    @ApiImplicitParams({@ApiImplicitParam(name = "catalogId", value = "课程ID", dataType = "String"),
            @ApiImplicitParam(name = "userId", value = "登录用户id", dataType = "String")})
    public void threeLevelDirectory(HttpServletResponse response, Integer userId, Integer catalogId) throws Exception {
        if (userId == null || catalogId == null) {
            throw new BusinessException(CommonErrorCode.E_200101);
        }
        log.info(LogUtil.LogInfo("查询专业大类3级目录", new Date()));
        Map<String, Object> appLogin = userFeign.selectByUserId(userId);
        List<Catalog> catalogs = catalogService.selectByParentId(catalogId);
        if (appLogin.get("CustomerType").equals("1")) {
            //1普通用户
            for (Catalog catalog : catalogs) {
                Map<String, Object> hashmap = new HashMap<>();
                hashmap.put("userId", userId);
                hashmap.put("catalogId", catalog.getCatalogId());
                UserCatalogBuy userCatalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(hashmap);
                if (userCatalogBuy == null) {
                    catalog.setIsRed("0");
                } else {
                    catalog.setIsRed("1");
                }
            }
            writeJSON(catalogs, response, "200", "成功");
        } else {
            //分配用户
            Map<String, Object> login = userFeign.selectBySchoolIdAndType(Integer.parseInt(appLogin.get("SchoolId").toString()), 2);//2 是用户类型
            for (Catalog catalog : catalogs) {
                Map<String, Object> hashmap = new HashMap<>();
                hashmap.put("userId", login.get("userId"));
                hashmap.put("catalogId", catalog.getCatalogId());
                UserCatalogBuy userCatalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(hashmap);
                if (userCatalogBuy == null) {
                    catalog.setIsRed("0");
                } else {
                    catalog.setIsRed("1");
                }
                Map<String, Object> objectMap = new HashMap<>();
                objectMap.put("userId", userId);
                objectMap.put("catalogId", catalog.getCatalogId());
                UserCatalogBuy catalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(objectMap);
                if (catalogBuy != null) {
                    catalog.setIsRed("1");
                }
            }
            writeJSON(catalogs, response, "200", "成功");
        }
    }

    @GetMapping("/threeDetails")
    @ApiOperation("查询3级资源详情")
    public void threeDetails(HttpServletResponse response, String userId, Integer catalogId) throws IOException {
        log.info(LogUtil.LogInfo("查询3级资源详情", new Date()));
        Catalog catalog = catalogService.selectCatalogByCatalogId(catalogId);
        SysAppLogin sysAppLogin = loginService.selectSysAppLoginById(userId);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("schoolId", sysAppLogin.getSchoolId());
        map2.put("userType", "2");
        SysAppLogin appLogin = loginService.selectByDeptId(map2);
        Map<String, Object> map = new HashMap<>();
        map.put("catalogId", catalog.getParentId());
        map.put("userId", appLogin.getUserId());
        UserCatalogBuy userCatalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(map);
        if (userCatalogBuy != null) {
            writeJSON(catalog, response, "200", "success");
            if (catalog.getCatalogLearningNum() == null) {
                catalog.setCatalogLearningNum(1);
            } else {
                catalog.setCatalogLearningNum(catalog.getCatalogLearningNum() + 1);
            }
            catalogService.updateCataLog(catalog);
        } else {
            writeJSON("非法", response, "200", "success");
        }
    }

    @GetMapping("/info")
    @ApiOperation("查询课程详情")
    public void classInfo(Integer catalogId, HttpServletRequest request, HttpServletResponse response, Integer userId) throws Exception {
        log.info(LogUtil.LogInfo("查询课程详情", new Date()));
        if (userId == null || catalogId == null) {
            throw new BusinessException(CommonErrorCode.E_200101);
        }

        Catalog catalog = catalogService.classInfo(catalogId);
        Map<String, Object> map = userFeign.selectByUserId(userId);
        //登录
        //1普通用户
        if (map.get("CustomerType").equals("1")) {
            Map<String, Object> hashmap = new HashMap<>();
            hashmap.put("userId", userId);
            hashmap.put("catalogId", catalog.getCatalogId());
            UserCatalogBuy userCatalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(hashmap);
            if (userCatalogBuy == null) {
                catalog.setIsRed("0");
            } else {
                catalog.setIsRed("1");
            }
        } else {
            //2线下分配用户
            //Map<String, Object> map2 = new HashMap<>();
            //map2.put("schoolId", appLogin.getSchoolId());
            //map2.put("userType", "2");
            //SysAppLogin login = loginService.selectByDeptId(map2);
            Map<String, Object> user = userFeign.selectBySchoolIdAndType((Integer) map.get("SchoolId"), 2);

            Map<String, Object> hashmap = new HashMap<>();
            hashmap.put("userId", userId);
            hashmap.put("catalogId", catalog.getCatalogId());
            UserCatalogBuy userCatalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(hashmap);
            if (userCatalogBuy == null) {
                catalog.setIsRed("0");
            } else {
                catalog.setIsRed("1");
            }
            Map<String, Object> objectMap = new HashMap<>();
            objectMap.put("userId", userId);
            objectMap.put("catalogId", catalog.getCatalogId());
            UserCatalogBuy catalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(objectMap);
            if (catalogBuy != null) {
                catalog.setIsRed("1");
            }
        }
        //浏览次数加一
        if (catalog.getCatalogLearningNum() == null) {
            catalog.setCatalogLearningNum(1);
        } else {
            catalog.setCatalogLearningNum(catalog.getCatalogLearningNum() + 1);
        }
        catalogService.updateCataLog(catalog);
        Catalog catalog1 = catalogService.selectCatalogInfoById(catalog.getParentId());
        catalog.setTwoJi(catalog1.getName());

        Catalog catalog2 = catalogService.selectCatalogInfoById(catalog1.getParentId());
        if (catalog2 != null) {
            catalog.setOneJi(catalog2.getName());
            //不隐藏
            catalog.setHide("0");
        } else {
            catalog.setOneJi(catalog.getName());
            //隐藏
            catalog.setHide("1");
        }
        //0未收藏 1已收藏
        isLike(userId, catalog);
        writeJSON(catalog, response, "200", "success");
    }

    //////////////********教学课件*************//////////////////
    @GetMapping("/type")
    @ApiOperation("查询素材课件信息")
    public void selectByType(HttpServletResponse response, String catalogId, String userId, String type, Integer pageNum, Integer pageSize) throws IOException {
        log.info(LogUtil.LogInfo("查询素材课件信息", new Date()));
        Map<String, Object> hashmap = new HashMap<>();
        hashmap.put("userId", userId);
        hashmap.put("catalogId", catalogId);
        UserCatalogBuy userCatalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(hashmap);
        if (userCatalogBuy != null) { //检查是否购买
            Map<String, Object> map = new HashMap<>();
            map.put("rCatalogid", catalogId);
            map.put("type", type);
            if (pageNum != null && pageSize != null) {
                PageHelper.startPage(pageNum, pageSize);
            }
            List<Resources> list = resourcesService.selectInfoByType(map);
            PageInfo<Resources> page = new PageInfo<>(list);
            writeJSON(page, response, "200", "success");
        } else {
            writeJSON(null, response, "200", "权限不足，请购买");
        }
    }

    ////////////////////////************查询专业课程目录已经虚拟教学***userId用于查询该目录是否购买 购买后才可以查看到虚拟教学********////////////////////////
    @GetMapping("/virtualTeaching")
    public void virtualTeaching(HttpServletResponse response, Integer catalogId, String userId, Integer pageNum, Integer pageSize) throws IOException {
        log.info(LogUtil.LogInfo("查询章节信息", new Date()));
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        if (catalogId == null) {
            catalogId = 0;
        }
        List<Catalog> catalogs = catalogService.selectByParentId(catalogId);
        for (Catalog catalog : catalogs) {
            Map<String, Object> map = new HashMap<>();
            map.put("rCatalogid", catalog.getCatalogId());
            Map<String, Object> hashmap = new HashMap<>();
            hashmap.put("userId", userId);
            hashmap.put("catalogId", catalogId);
            UserCatalogBuy userCatalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(hashmap);//检查是否购买
            List<Resources> resources = resourcesService.selectVideoById(map);//查找视频资源
            if (userCatalogBuy != null) {
                //8 3D动画 9 FLASH 动画
                for (Resources resource : resources) {
                    if (resource.getType().equals("9")) {
                        catalog.setFlash(resource.getrUrl());
                    } else if (resource.getType().equals("8")) {
                        catalog.setThreeD(resource.getrUrl());
                    }
                }
            }
        }
        writeJSON(new PageInfo<>(catalogs), response, "200", "success");
    }

    @PostMapping("/addSave")
    @ApiOperation("发布课后评价")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "plText", value = "评论内容", required = true, dataType = "String"),
            @ApiImplicitParam(name = "plCreateuser", value = "发布人", required = true, dataType = "String"),
            @ApiImplicitParam(name = "plCurriculumid", value = "课程编号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "plImage", value = "评论图片", required = true, dataType = "String"),
            @ApiImplicitParam(name = "plAttribute", value = "属性标签编号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "plPraise", value = "1：好评，2：中评，3：差评", required = true, dataType = "String")})
    public void addSave(HttpServletResponse response, Comments comments) throws Exception {
        log.info(LogUtil.LogInfo("发布课后评价", new Date()));
        comments.setPlId(UUIDUtils.getByUUId());
        comments.setPlCreatetime(new Date());
        commentsService.insertComments(comments);
        writeJSON("添加成功", response, "200", "成功");
    }

    @GetMapping("/allEvaluation")
    @ApiOperation("查询全部评价")
    public void list(HttpServletResponse response, Integer catalogId) throws IOException {
        log.info(LogUtil.LogInfo("查询全部评价", new Date()));
        List<Comments> comments = commentsService.selectByCatalogId(catalogId);
        //好评
        Integer good = 0;
        //中评
        Integer average = 0;
        //差评
        Integer badReview = 0;
        for (Comments comment : comments) {
            if (comment.getPlPraise().equals("1")) {
                good++;
            } else if (comment.getPlPraise().equals("2")) {
                average++;
            } else if (comment.getPlPraise().equals("3")) {
                badReview++;
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("good", good);
        map.put("average", average);
        map.put("badReview", badReview);
        writeJSON(map, response, "200", "成功");
    }

    @GetMapping("/screeningEvaluation")
    @ApiOperation("筛选好，中，差评价")
    public void screeningEvaluation(HttpServletResponse response, Integer catalogId, String type, Integer
            pageSize, Integer pageNum) throws IOException {
        log.info(LogUtil.LogInfo("筛选好，中，差评价", new Date()));
        Map<String, Object> map = new HashMap<>();
        map.put("catalogId", catalogId);
        map.put("type", type);
        PageHelper.startPage(pageNum, pageSize);
        List<Comments> comments = commentsService.selectByType(map);
        for (Comments comment : comments) {
            SysAppLogin sysAppLogin = loginService.selectSysAppLoginById(comment.getPlCreateuser());
            comment.setUserName(sysAppLogin.getUserAccount());
            comment.setUserIcoUrl(sysAppLogin.getUserIco());
            Label label = labelService.selectLabelById(comment.getPlAttribute());
            if (label != null) {
                comment.setLabelName(label.getBqLabel());
            }
        }
        writeJSON(new PageInfo<>(comments), response, "200", "成功");
    }

    @GetMapping("/labelScreening")
    @ApiOperation("按标签筛选评价")
    public void labelScreening(HttpServletResponse response, Integer catalogId, String labeId, Integer
            pageSize, Integer pageNum) throws IOException {
        log.info(LogUtil.LogInfo("按标签筛选评价", new Date()));
        Map<String, Object> map = new HashMap<>();
        map.put("catalogId", catalogId);
        map.put("labeId", labeId);
        PageHelper.startPage(pageNum, pageSize);
        List<Comments> comments = commentsService.selectByLabeId(map);
        for (Comments comment : comments) {
            SysAppLogin sysAppLogin = loginService.selectSysAppLoginById(comment.getPlCreateuser());
            sysAppLogin.setUserPassword(null);
            comment.setSysAppLogin(sysAppLogin);
        }
        writeJSON(new PageInfo<>(comments), response, "200", "成功");
    }

    @PostMapping("/addLikeCatalogs")
    @ApiOperation("用户点小红心收藏该课程")
    public void addLikeCatalogs(HttpServletResponse response, Integer catalogId, String userId) throws Exception {
        log.info(LogUtil.LogInfo("用户新增喜欢的课程", new Date()));
        CatalogUserLike userLike = new CatalogUserLike();
        userLike.setCatalogId(catalogId);
        userLike.setUserId(userId);
        if (userId != null && userId != "") {
            List<CatalogUserLike> catalogUserLikes = userLikeService.selectCatalogUserLikeList(userLike);
            if (catalogUserLikes != null && catalogUserLikes.size() > 0) {
                collectionsService.deleteCollectionByIds(catalogUserLikes.get(0).getCatalogId().toString());
            } else {
                userLike.setCreateTime(new Date());
                //删除标记 0 未删除
                userLike.setDelFlag("0");
                //状态 0 学习中 1 已学完
                userLike.setState("0");
                //插入到用户喜欢课程表中
                userLikeService.insertCatalogUserLike(userLike);
            }
            writeJSON(null, response, "200", "成功");
        } else {
            writeJSON("未登录，请登录", response, "201", "成功");
        }
        //Collections collections = new Collections();
        //collections.setSzUserloginid(userId);
        //collections.setSzLtid(id);
       /* if (userId != null) {
            List<Collections> collectionsList = collectionsService.selectCollectionList(collections);
            if (collectionsList != null && collectionsList.size() > 0) {
                collectionsService.deleteCollectionByIds(collectionsList.get(0).getSzId().toString());
            } else {
                collections.setSzCollectiontime(new Date());
                collectionsService.insertCollection(collections);
            }
            writeJSON(null, response, "200", "成功");
        } else {
            writeJSON("未登录，请登录", response, "201", "成功");
        }*/
    }

    @GetMapping("/whetherLike")
    @ApiOperation("查询用户是否已收藏该课程")
    public void whetherLike(HttpServletResponse response, Integer id, String userId) throws IOException {
        log.info(LogUtil.LogInfo("查询用户是否已收藏该课程", new Date()));
        if (id != null && userId != null && !"".equals(userId)) {
            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
            stringObjectHashMap.put("userId", userId);
            stringObjectHashMap.put("catalogId", id);

            CatalogUserLike userLike = userLikeService.selectByMap(stringObjectHashMap);
            Map<String, Object> map = new HashMap<>();
            //根据userId 和 catalogId 查询收藏表，判断该用户是否收藏该课程
            if (userLike != null) {
                map.put("whether", "1");
                writeJSON(map, response, "200", "success");
            } else {
                map.put("whether", "0");
                writeJSON(map, response, "200", "success");
            }
           /* Collections collections = new Collections();
            collections.setSzUserloginid(userId);
            collections.setSzLtid(id);
            Map<String, Object> map = new HashMap<>();
            if (userId != null && userId.length() > 0) {
                List<Collections> collectionsList = collectionsService.selectCollectionList(collections);
                if (collectionsList != null && collectionsList.size() > 0) {
                    map.put("whether", "1");
                    writeJSON(map, response, "200", "success");
                } else {
                    map.put("whether", "0");
                    writeJSON(map, response, "200", "success");
                }
            } else {
                map.put("whether", "0");
                writeJSON(map, response, "200", "success");
            }*/
        }
        writeJSON(null, response, "200", "缺少该课程id或用户id");
    }

    /**
     * 查询试卷列表
     */
    @GetMapping("/paperList")
    @ApiOperation("查询专业课程详情下的试卷")
    @ApiImplicitParams({@ApiImplicitParam(name = "catalogId", value = "参数集合", dataType = "String")})
    public void paperlist(HttpServletResponse response, String catalogId, Integer pageSize, Integer pageNum) throws Exception {
        log.info(LogUtil.LogInfo("查询专业课程详情下的试卷", new Date()));
        Map<String, Object> map = new HashMap<>();
        map.put("catalogId", catalogId);
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<Paper> list = paperService.selectPaperListById(map);
        writeJSON(new PageInfo<>(list), response, "200", "成功");
    }

    ////////////////////***********搜索接口****************//////////////////////////////////
    @GetMapping("/search")
    public void search(HttpServletResponse response, String name, Integer pageSize, Integer pageNum, Integer userId) throws IOException {
        log.info(LogUtil.LogInfo("搜索", new Date()));
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<Catalog> list = catalogService.selectByLikeName(name);
        for (Catalog catalog : list) {
            if (userId == null) {
                catalog.setIsRed("0");
            } else {
                //SysAppLogin sysAppLogin = loginService.selectSysAppLoginById(userId);
                //Map<String, Object> map2 = new HashMap<>();
                //map2.put("schoolId", map2.get("SchoolId"));
                //map2.put("userType", "2");
                //SysAppLogin appLogin = loginService.selectByDeptId(map2);
                Map<String, Object> user = userFeign.selectByUserId(userId);
                Map<String, Object> map1 = userFeign.selectBySchoolIdAndType((Integer) user.get("SchoolId"), 2);
                //查询用户是否购买 1 已购买 0 未购买
                Map<String, Object> map = new HashMap<>();
                map.put("catalogId", catalog.getParentId());
                map.put("userId", map1.get("userId"));
                UserCatalogBuy userCatalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(map);
                if (userCatalogBuy != null) {
                    catalog.setIsRed("1");
                } else {
                    catalog.setIsRed("0");
                }
            }
        }
        writeJSON(new PageInfo<>(list), response, "200", "成功");
    }

    /**
     * 今软PC端老师购买专业课程资源
     *
     * @param response
     * @param catalogBuy
     * @throws IOException
     */
    @PostMapping("/addBatch")
    @ApiOperation("新增购买目录")
    @Transactional(rollbackFor = Exception.class)
    public void addBatch2(HttpServletResponse response, @RequestBody UserCatalogBuy catalogBuy) throws IOException {
        //根据catalogId查询目录体系表
        Catalog catalog = catalogService.selectCatalogByCatalogId(catalogBuy.getCatalogId());
        //根据userId查询用户信息
        //UserAccount userAccount = accountService.selectUserAccountByUserId(catalogBuy.getUserId());
        Map<String, Object> user = userFeign.selectByUserId(Integer.parseInt(catalogBuy.getUserId()));
        //获取达人币数量
        BigDecimal currency = new BigDecimal(user.get("price").toString());
        //获取原价信息
        BigDecimal price = new BigDecimal(catalog.getPrice());
        //查询该用户购买了那些课程
        Map<String, Object> map = new HashMap<>();
        map.put("userId", catalogBuy.getUserId());
        map.put("catalogId", catalogBuy.getCatalogId());
        UserCatalogBuy userCatalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(map);
        if (userCatalogBuy == null) {
            //if (currency >= price) {
            if (currency.compareTo(price) >= 0) {
                //查询该目录是否是3级目录  不是就无法购买
                List<Catalog> catalogs = catalogService.selectByCatalogIdAndSort(catalog.getCatalogId(), 3);
                if (catalogs.size() == 0) {
                    writeJSON("不是课程 无法购买", response, "300", "fail");
                } else {
                    //UserAccount uaccount = new UserAccount();
                    //uaccount.setCurrency(currency - price);
                    //uaccount.setUserId(catalogBuy.getUserId());
                    //accountService.updateUserAccount(uaccount);
                    Map<String, Object> mp = new HashMap<>();
                    mp.put("id", catalogBuy.getUserId());
                    //mp.put("price", currency - price);
                    mp.put("price", currency.subtract(price));
                    //消耗达人币购买课程
                    //userFeign.updataByUserId(mp);
                    userFeign.updatePriceByUserId(Integer.parseInt(catalogBuy.getUserId()), currency.subtract(price));

                    //发布该课程用户添加达人币收入 中间表
                    CatalogUser catalogUser = new CatalogUser();
                    catalogUser.setCatalogId(catalog.getCatalogId());
                    List<CatalogUser> catalogUsers = catalogUserService.selectCatalogUserList(catalogUser);
                    if (catalogUsers.size() > 0) {
                        String userId = catalogUsers.get(0).getUserId().toString();
                        Map<String, Object> user1 = userFeign.selectByUserId(Integer.parseInt(userId));
                        //获取达人币数量
                        BigDecimal currency1 = new BigDecimal(user1.get("price").toString());
                        mp.put("id", userId);
                        //mp.put("price", currency1 + price);
                        mp.put("price", currency1.add(price));
                        //添加达人币
                        userFeign.updatePriceByUserId(Integer.parseInt(userId), currency1.add(price));
                    }

                    //TODO 专业课程体系下购买资源后同步到我的资源库
                    userCatalogBuyService.professionalCoursesSynchronousMineRes(catalogBuy.getCatalogId(), catalogBuy.getUserId());

                    catalogBuy.setDeflag("1");//未删除
                    catalogBuy.setItFrom(1);
                    userCatalogBuyService.insert(catalogBuy);

                    //添加支付记录
                    CurrencyRecord record = new CurrencyRecord();
                    record.setCreateTime(new Date());
                    record.setEditTime(new Date());
                    record.setUserId(catalogBuy.getUserId());
                    record.setPayerName(user.get("name").toString());
                    record.setCurrency(new BigDecimal(catalogs.get(0).getPrice()));
                    record.setRemark("专业课程购买");
                    record.setStatus("1");
                    record.setCatalogId(catalog.getCatalogId());
                    record.setTrxType("3");
                    //订单id
                    record.setCurrencyId(nextItemNo());
                    record.setOrderType("1");
                    currencyRecordService.insertCurrencyRecord(record);

                    //添加购买消息
                    Message message = new Message();
                    message.setIsRead("1");
                    message.setUserId(Integer.parseInt(catalogBuy.getUserId()));
                    message.setType("1");
                    message.setCreatetime(new Date());
                    message.setTitle("您已购买课程 : " + catalogs.get(0).getName());
                    messageService.insertMessage(message);
                    //发送消息
                    Integer count = messageService.selectCount(catalogBuy.getUserId());
                    try {
                        WebSocketServer.sendInfo(count.toString(), catalogBuy.getUserId());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //writeJSON(currency - price, response, "200", "购买成功");
                writeJSON(currency.subtract(price), response, "200", "购买成功");
            } else {
                writeJSON("账户余额不足", response, "300", "购买失败");
            }
        } else {
            writeJSON("已经购买", response, "300", "购买失败");
        }
    }

    /**
     * 订单号生成   20200718112629527
     */
    public static String nextItemNo() {
        LocalDateTime dateTime = LocalDateTime.now();
        return DateLiuUtil.getOtherFormatterLocalDateTime(dateTime);
    }

    /* ----------- 将智慧云课堂备课中心章或者节 以及下面的资源同步到今软平台 -----------*/

    /**
     * 添加目录 父级目录 接受章节id数组 要同步到的今软目录id 达人币数量
     */
    @PostMapping("/addOther")
    public void addCatalog(@RequestBody CatalogResultVO resultVO) {
        //已经有三个参数
        Catalog catalog = Catalog.builder()
                .name(resultVO.getName() != null ? resultVO.getName() : "")
                .parentId(resultVO.getParentId())
                .price(resultVO.getPrice()).catalogSort(3)
                .delFlag("0").createTime(new Date()).catalogState(1)
                .studysum("0").catalogIco("1597476296318.jpg").build();
        //进行添加
        catalogService.insertCatalog(catalog);
        //新添加 自动生成的主键id
        Integer catalogId = catalog.getCatalogId();
        Integer catalogId6 = null;
        //Catalog catalog2 = null;
        //往用户和课程关联的中间表中添加数据
        String userId = resultVO.getUserId();
        CatalogUser catalogUser = new CatalogUser();
        catalogUser.setCatalogId(catalogId);
        catalogUser.setUserId(userId);
        catalogUser.setCreateTime(new Date());
        catalogUser.setDelFlag("0");
        catalogUser.setState("0");
        catalogUserService.insertCatalogUser(catalogUser);

        //添加资源  查询出来进行传递
        List<OResources> resList = resultVO.getResList();
        //添加资源
        if (resList.size() > 0) {
            //往catalog表中添加数据
            Resources resources = new Resources();
            for (OResources oResources : resList) {
                BeanUtils.copyProperties(oResources, resources);
                resources.setId(null);
                resources.setCreateTime(new Date());
                resources.setrCatalogid(catalogId);
                /**
                 *     今软类别      1 教学课件  3 技术文档   4 实操视频      5 实战照片    8，9 虚拟教学
                 *     智慧云类别    1 教学课件  2 技术文档   5 真人实操视频  4 图片        8 虚拟教学
                 */
                if ("6".equals(resources.getType()) || "7".equals(resources.getType())) {
                    //if (catalog2 == null) {
                    Catalog catalog2 = new Catalog();
                    catalog2.setParentId(catalogId);
                    catalogService.insertCatalog(catalog2);
                    catalogId6 = catalog2.getCatalogId();
                    //}
                    if ("6".equals(resources.getType())) {
                        resources.setrCatalogid(catalogId6);
                        resources.setType("8");
                        resourcesService.insertResources(resources);
                    }
                    if ("7".equals(resources.getType())) {
                        resources.setrCatalogid(catalogId6);
                        resources.setType("9");
                        resourcesService.insertResources(resources);
                    }
                }

                switch (resources.getType()) {
                    case "2":
                        resources.setType("3");
                        resourcesService.insertResources(resources);
                        break;
                    case "5":
                        resources.setType("4");
                        resourcesService.insertResources(resources);
                        break;
                    case "4":
                        resources.setType("5");
                        resourcesService.insertResources(resources);
                        break;
                    default:
                        //1 8
                        resourcesService.insertResources(resources);
                        break;
                }
            }
        }
        List<SQuestionsVO> questionsList = resultVO.getQuestionsList();
        if (questionsList.size() > 0) {
            //先添加试卷 获取自动生成的主键
            Paper paper = new Paper();
            paper.setCatalogId(catalogId);
            paper.setCreateTime(new Date());
            //课程名称 + 测试
            paper.setSjIntroduction(resultVO.getPaperName() + "测试");
            //总分
            paper.setSjScore(new BigDecimal("60"));
            paperService.insertPaperOne(paper);
            Integer pId = paper.getId();
            //再添加试题
            Questions questions = new Questions();
            for (SQuestionsVO sQuestionsVO : questionsList) {
                BeanUtils.copyProperties(sQuestionsVO, questions);
                questions.setId(null);
                questions.setStScore(new BigDecimal("10"));
                questionsService.insertQuestions(questions);
                //获取自动生成的主键
                Integer qId = questions.getId();
                //往试卷 试题关联表中添加数据
                JrPaperQueRelation paperQuestion = new JrPaperQueRelation();
                paperQuestion.setPaperId(pId);
                paperQuestion.setQuestionId(qId);
                queRelationService.insertJrPaperQueRelation(paperQuestion);
            }
        }

        //把分享的课程添加到该学校所有老师购买目录
        Map<String, Object> map = userFeign.selectByUserId(Integer.parseInt(resultVO.getUserId()));//查询学校id
        List<Integer> list = userFeign.selectBySchooleId((Integer) map.get("SchoolId"));
        for (Integer usId : list) {
            Map<String, Object> m = new HashMap<>();
            m.put("userId", usId);
            m.put("catalogId", catalogId);
            UserCatalogBuy catalogBuy = userCatalogBuyService.selectUserCatalogBuyByUserId(m);
            if (catalogBuy == null) {
                UserCatalogBuy userCatalogBuy = new UserCatalogBuy();
                userCatalogBuy.setCatalogId(catalogId);
                userCatalogBuy.setUserId(usId.toString());
                userCatalogBuy.setDeflag("1");
                userCatalogBuyService.insert(userCatalogBuy);
            }
        }
    }

    /**
     * 试卷试题数据添加
     */
    @GetMapping("/addData")
    public String addData(Integer paperId, Integer samllQuestionId, Integer bigQuestionId) {
        JrPaperQueRelation jrPaperQueRelation = new JrPaperQueRelation();
        jrPaperQueRelation.setPaperId(paperId);
        for (Integer i = samllQuestionId; i <= bigQuestionId; i++) {
            jrPaperQueRelation.setQuestionId(i);
            queRelationService.insertJrPaperQueRelation(jrPaperQueRelation);
        }
        return "添加成功";
    }

}
